package com.zcxy.edu.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zcxy.common.config.RuoYiConfig;
import com.zcxy.common.utils.DateUtils;
import com.zcxy.common.utils.http.HttpUtilsNew;
import com.zcxy.edu.domain.EduStudent;
import com.zcxy.edu.domain.EduTeacher;
import com.zcxy.edu.mapper.EduTeacherMapper;
import com.zcxy.system.domain.SysConfig;
import com.zcxy.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zcxy.edu.mapper.EduOrgMapper;
import com.zcxy.edu.domain.EduOrg;
import com.zcxy.edu.service.IEduOrgService;

/**
 * 院系组织Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-20
 */
@Service
public class EduOrgServiceImpl implements IEduOrgService
{
    @Autowired
    private EduOrgMapper eduOrgMapper;

    @Autowired
    private EduTeacherMapper eduTeacherMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    private static final Logger log = LoggerFactory.getLogger(EduOrgServiceImpl.class);

    /**
     * 查询院系组织
     *
     * @param id 院系组织主键
     * @return 院系组织
     */
    @Override
    public EduOrg selectEduOrgById(Long id)
    {
        return eduOrgMapper.selectEduOrgById(id);
    }

    /**
     * 查询院系组织列表
     *
     * @param eduOrg 院系组织
     * @return 院系组织
     */
    @Override
    public List<EduOrg> selectEduOrgList(EduOrg eduOrg)
    {
        return eduOrgMapper.selectEduOrgList(eduOrg);
    }

    /**
     * 新增院系组织
     *
     * @param eduOrg 院系组织
     * @return 结果
     */
    @Override
    public int insertEduOrg(EduOrg eduOrg)
    {
        EduOrg edu = new EduOrg();
        edu.setDWH(eduOrg.getDWH());
        List<EduOrg> eduStudentList = eduOrgMapper.selectEduOrgList(edu);
        if(eduStudentList.size() == 0){
            eduOrg.setCreateTime(DateUtils.getNowDate());
            return eduOrgMapper.insertEduOrg(eduOrg);
        }else{
            eduOrg.setId(eduStudentList.get(0).getId());
            eduOrg.setUpdateTime(DateUtils.getNowDate());
            return eduOrgMapper.updateEduOrg(eduOrg);
        }
    }

    /**
     * 修改院系组织
     *
     * @param eduOrg 院系组织
     * @return 结果
     */
    @Override
    public int updateEduOrg(EduOrg eduOrg)
    {
        eduOrg.setUpdateTime(DateUtils.getNowDate());
        return eduOrgMapper.updateEduOrg(eduOrg);
    }

    /**
     * 批量删除院系组织
     *
     * @param ids 需要删除的院系组织主键
     * @return 结果
     */
    @Override
    public int deleteEduOrgByIds(Long[] ids)
    {
        return eduOrgMapper.deleteEduOrgByIds(ids);
    }

    /**
     * 删除院系组织信息
     *
     * @param id 院系组织主键
     * @return 结果
     */
    @Override
    public int deleteEduOrgById(Long id)
    {
        return eduOrgMapper.deleteEduOrgById(id);
    }


    /**
     * 自动刷新数据
     */
    public void selectAndSaveApiData() throws UnsupportedEncodingException {
        String page = sysConfigService.selectConfigByKey("orgDataPage");
        int pageNumber = Integer.parseInt(page);

        String url = RuoYiConfig.getStudentPath();
        url += "?token="+sysConfigService.selectConfigByKey("eduToken");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id","7855e490549511ef1672576b3e52e1b5");
        jsonObject.put("pageIndex", pageNumber);
        jsonObject.put("params",new JSONArray(new JSONObject()));

        String encodedUrl = URLEncoder.encode(jsonObject.toJSONString(), StandardCharsets.UTF_8.toString());
        url += "&jsonStr="+encodedUrl;

        log.info("请求获取组织信息地址参数:"+url);
        String result = HttpUtilsNew.sendGet(url,"","",null);
        log.info("请求获取组织信息结果"+result);

        JSONObject resultData = JSONObject.parseObject(result);
        if(resultData.getInteger("status") != 200){
            return;
        }

        JSONObject data = resultData.getJSONObject("data");

        if(data.getInteger("totalCount")==eduOrgMapper.eduOrgCount()){
            return;
        }else {
            pageNumber++;
        }

        JSONArray jsonArray = data.getJSONArray("list");
        for(Object obj : jsonArray){
            JSONObject json = (JSONObject) obj;
            EduOrg eduOrg = JSON.toJavaObject(json, EduOrg.class);
            insertEduOrg(eduOrg);
        }

        SysConfig sysConfig = new SysConfig();
        sysConfig.setConfigKey("orgDataPage");
        List<SysConfig> list = sysConfigService.selectConfigList(sysConfig);
        list.get(0).setConfigValue(pageNumber+"");
        sysConfigService.updateConfig(list.get(0));
    }

    public List<Map<String,Object>> getTreeData(){
        List<Map<String,Object>> allList = new ArrayList<Map<String,Object>>();

        List<Map<String,Object>> firstOrgs = eduOrgMapper.selectLastOrg("21000000");

        for(Map<String,Object> firstOrg : firstOrgs){
            Map<String,Object> map = new HashMap<>();
            map.put("id", firstOrg.get("DWH"));
            map.put("label", firstOrg.get("DWMC"));

            List<Map<String,Object>> secondOrgs = eduOrgMapper.selectLastOrg(firstOrg.get("DWH")+"");
            List<Map<String,Object>> secondList = new ArrayList<Map<String,Object>>();
            for(Map<String,Object> secondOrg : secondOrgs){
                Map<String,Object> mapS = new HashMap<>();
                mapS.put("id", secondOrg.get("DWH"));
                mapS.put("label", secondOrg.get("DWMC"));

                List<Map<String,Object>> thirdOrgs = eduOrgMapper.selectLastOrg(secondOrg.get("DWH")+"");
                List<Map<String,Object>> thirdList = new ArrayList<Map<String,Object>>();
                for(Map<String,Object> thirdOrg : thirdOrgs){
                    Map<String,Object> mapT = new HashMap<>();
                    mapT.put("id", thirdOrg.get("DWH"));
                    mapT.put("label", thirdOrg.get("DWMC"));
                    thirdList.add(mapT);
                }
                mapS.put("children", thirdList);
                secondList.add(mapS);
            }
            map.put("children", secondList);
            allList.add(map);
        }
//        List<Map<String,Object>> orgs = eduOrgMapper.selectAllOrg();
//        for(Map<String,Object> eduOrg : lastOrgs){
//            Map<String,Object> map = new HashMap<>();
//            map.put("id", eduOrg.get("LSDWH"));
//
//            List<Map<String,Object>> orgList = new ArrayList<Map<String,Object>>();
//            for(Map<String,Object> org :  orgs){
//                if(eduOrg.get("LSDWH").equals(org.get("LSDWH"))){
//                    Map<String,Object> mapT = new HashMap<>();
//                    map.put("label", org.get("DWMC"));
//                    mapT.put("id", org.get("DWH"));
//                    mapT.put("label", org.get("DWMC"));
//                    orgList.add(mapT);
//                }
//            }
//            map.put("children", orgList);
//
//            allList.add(map);
//        }
        return allList;
    }
}
